// api/auth.ts
import apiClient from './index';

// 登录请求参数类型
interface LoginParams {
  username: string;
  password: string;
}

// 登录响应数据类型
interface LoginResponse {
  code: number;
  content: {
    token: string;
  };
  msg: string;
}

/**
 * 用户登录
 */
export const login = async (params: LoginParams): Promise<LoginResponse> => {
  const response = await apiClient.post<LoginResponse>('/auth/login', params);
  if (response.data.code === 200 && response.data.content.token) {
    localStorage.setItem('token', response.data.content.token);
  }
  return response.data;
};

// 忘记密码请求参数类型
interface ForgotPasswordParams {
  admin_password: string;
  new_password: string;
}

// 忘记密码响应数据类型
interface ForgotPasswordResponse {
  code: number;
  content?: string;
  msg: string;
}

/**
 * 忘记密码通过口令重设
 */
export const forgotPassword = async (
  params: ForgotPasswordParams
): Promise<ForgotPasswordResponse> => {
  const response = await apiClient.post<ForgotPasswordResponse>(
    '/auth/forgot-password',
    params
  );
  return response.data;
};

interface UserBasicResponse {
  name: string;
  role: string;
  user_id: number;
}

/**
 * 获取用户基本信息
 */
export const getBasicUserInfo = async (): Promise<UserBasicResponse> => {
  const response = await apiClient.get<UserBasicResponse>('/test');
  return response.data;
}

/**
 * 修改自己密码
 */
interface ChangePasswordParams {
  old_password: string;
  new_password: string;
}

interface ChangePasswordResponse {
  code: number;
  content?: string;
  msg: string;
} 

export const changePassword = async (
  params: ChangePasswordParams
): Promise<ChangePasswordResponse> => {
  const response = await apiClient.post<ChangePasswordResponse>(
    '/auth/change-password',
    params
  );
  return response.data;
}

// 新增修改口令接口
export interface ChangePasswordKeyParams {
  old_password_key: string;
  login_password: string;
  new_password_key: string;
}

export interface ChangePasswordKeyResponse {
  code: number;
  msg: string;
}

export const changePasswordKey = async (
  params: ChangePasswordKeyParams
): Promise<ChangePasswordKeyResponse> => {
  const response = await apiClient.post<ChangePasswordKeyResponse>(
    '/auth/change-password-key',
    params
  );
  return response.data;
};